import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('../views/HomeView.vue')
    },
    {
      path: '/cur',
      name: 'cur',
      component: () => import('../views/Current.vue')
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/Register.vue')
    },
    {
      path: '/MusicDetail/:id',
      name: 'MusicDetail',
      component: () => import('../views/MusicDetail.vue')
    },
    {
      path: '/findmusic',
      name: 'findmusic',
      component: () => import('../views/FindMusic.vue')
    },
    {
      path: '/mymusic',
      name: 'mymusic',
      component: () => import('../views/MyMusic.vue')
    },
    {
      path: '/userinfo',
      name: 'userinfo',
      component: () => import('../views/UserInfo.vue')
    },
    {
      path: '/playlist/:id',
      name: 'playlist',
      component: () => import('../views/PlayList.vue')
    },
    {
      path: '/mv/:id',
      name: 'mv',
      component: () => import('../views/MvView.vue')
    },
    {
      path: '/admin',
      name: 'Admin',
      component: () => import('../views/AdminDashboard.vue'),
      meta: { 
        requiresAuth: true,
        isAdmin: true 
      }
    }
  ],
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 获取本地存储中的用户信息
  const userToken = localStorage.getItem('userToken');
  const isAdmin = localStorage.getItem('is_admin') === '1';

  // 检查是否需要管理员权限
  if (to.matched.some(record => record.meta.isAdmin)) {
    // 必须同时满足已登录和是管理员
    if (!userToken) {
      ElMessage.warning('请先登录')
      next('/')
      return
    }
    
    if (!isAdmin) {
      ElMessage.warning('需要管理员权限')
      next(from.path || '/') // 退回上一页或主页
      return
    }
    
    next() // 通过验证，继续路由
    return
  }

  // 检查是否需要普通用户登录
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!userToken) {
      ElMessage.warning('请先登录')
      next('/')
      return
    }
  }
  
  next() // 其他情况直接通过
})

export default router
